import json

from flask_sqlalchemy import SQLAlchemy
from packages.core.db.decorators import Transactional
from packages.core.auth.login_user_holder import LoginUserHolder
from modules.dev.models.schema_field import SchemaField
from packages.tools.base_tool import generate_id, underline_to_camel
from packages.tools.db_tool import DbTool
from packages.common.base import IdForm, IdsForm
from modules.dev.validators.schema_field_validator import SchemaFieldForm, SchemaFieldPageForm


class SchemaFieldService():
    """
    模型字段模块业务处理类
    """
    def __init__(self, db: SQLAlchemy):
        self.model = SchemaField
        self.db = db

    def detail(self, form: IdForm):
        """
        模型字段详情
        """
        model = self.db.session.query(self.model).get(form.id.data)
        if model is None:
            return {}
        return model.to_dict(SchemaFieldService.to_vo)

    def page(self, form: SchemaFieldPageForm):
        # 重写分页查询，追加roleIds字段
        pageNum = form.data.get("pageNum", 1)
        pageSize = form.data.get("pageSize", 10)
        page = DbTool.filter_by_custom(self.model).paginate(page=pageNum, per_page=pageSize, error_out=False)
        res = self.model.to_page(page, SchemaFieldService.to_vo)
        return res

    @Transactional()
    def save(self, form: SchemaFieldForm):
        """
        添加数据模型字段
        :param form:
        :return:
        """
        model = self.model(**form.data)
        model.id = generate_id()
        model.createUser = LoginUserHolder.get_user_id()
        model.updateUser = LoginUserHolder.get_user_id()
        model.variable = json.dumps(form.ext.data, ensure_ascii=False)
        self.db.session.add(model)

    @Transactional()
    def update(self, form: SchemaFieldForm):
        """
        修改数据模型
        :param form:
        :return:
        """
        model = self.model(**form.data)
        model.updateUser = LoginUserHolder.get_user_id()
        model.variable = json.dumps(form.ext.data, ensure_ascii=False)
        self.db.session.query(self.model).filter_by(id=form.id.data).update(
            model.to_dict()
        )

    @Transactional()
    def remove(self, form: IdsForm):
        """
        删除
        :param form:
        :return:
        """
        self.model().remove(self.model, form.ids.data)

    def list_by_schema_id(self, schemaId):
        res = DbTool.filter_by_custom(self.model).filter_by(schemaId=schemaId).all()
        return SchemaField.to_dict_list(res, SchemaFieldService.to_vo)

    @staticmethod
    def to_vo(data):
        if "variable" in data:
            data["ext"] = json.loads(data["variable"])
        else:
            data['ext'] = {}
        data["fieldCamelName"] = underline_to_camel(data["fieldName"])
        return data
